package com.aksu.wiki.service;


import com.aksu.wiki.domain.Ebook;
import com.aksu.wiki.domain.EbookExample;
import com.aksu.wiki.mapper.EbookMapper;
import com.aksu.wiki.req.EbookQueryReq;
import com.aksu.wiki.req.EbookSaveReq;
import com.aksu.wiki.resp.EbookQueryResp;
import com.aksu.wiki.resp.PageResp;
import com.aksu.wiki.util.CopyUtil;
import com.aksu.wiki.util.SnowFlake;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class EbookService {

    @Resource
    private SnowFlake snowFlake;



    private static final Logger LOG = LoggerFactory.getLogger(EbookService.class);


    @Resource
    private EbookMapper ebookMapper;



    public PageResp<EbookQueryResp> getList(EbookQueryReq req) {

        PageHelper.startPage(req.getPage(), req.getSize());

        EbookExample ebookExample = new EbookExample();
        EbookExample.Criteria criteria = ebookExample.createCriteria();
        if(!ObjectUtils.isEmpty(req.getName())){
            criteria.andNameLike("%"+req.getName()+"%");
        }
        if(!ObjectUtils.isEmpty(req.getCategoryId2())){
            criteria.andCategory2IdEqualTo(req.getCategoryId2());
        }


        List<Ebook> ebookList = ebookMapper.selectByExample(ebookExample);

        PageInfo<Ebook> pageInfo = new PageInfo<>(ebookList);
        LOG.info("总行数:{}",pageInfo.getTotal());
        LOG.info("总页数:{}",pageInfo.getPages());

        PageResp<EbookQueryResp> pageResp = new PageResp();

        List<EbookQueryResp> ebookResps = CopyUtil.copyList(ebookList, EbookQueryResp.class);
        pageResp.setList(ebookResps);
        pageResp.setTotal(pageInfo.getTotal());

        return  pageResp;

    }


    /**
     * 保存
     */
    public void save(EbookSaveReq req) {
        Ebook ebook = CopyUtil.copy(req, Ebook.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            // 新增
            ebook.setDocCount(0);
            ebook.setVoteCount(0);
            ebook.setViewCount(0);
            ebook.setId(snowFlake.nextId());
            ebookMapper.insert(ebook);
        } else {
            // 更新
            LOG.info("更新ebook:{}",ebook);
            ebookMapper.updateByPrimaryKey(ebook);
        }
    }

    public void delete(Long id) {
        ebookMapper.deleteByPrimaryKey(id);
    }

}
